package com.itheima.case2.web;

import com.itheima.case2.pojo.po.User;
import com.itheima.case2.pojo.vo.Result;
import com.itheima.case2.service.UserServiceImpl_1;
import com.itheima.case2.utils.BaseController;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String htmlInputCode = request.getParameter("code");
        System.out.println(request.getSession().getId());
        String sessionCheckCode = (String) request.getSession().getAttribute("checkcode");
        if (sessionCheckCode.equalsIgnoreCase(htmlInputCode)){
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            user.setEmail(email);
            UserServiceImpl_1 userService = new UserServiceImpl_1();
            boolean result1 = userService.register(user);

            if(result1){
                //创建Result对象存储返回信息
                Result result = new Result(true, "恭喜你注册成功");
                //响应给前端
                BaseController.printResult(response, result);
            }else{
                //创建Result对象存储返回信息
                Result result = new Result(false, "用户名存在，注册失败");
                //响应给前端
                BaseController.printResult(response, result);
            }
        }else {
            //创建Result对象存储返回信息
            Result result = new Result(false, "验证码错误，注册失败");
            //响应给前端
            BaseController.printResult(response, result);
        }

    }
}
